/*
 * Licensed to Nanjing RedOrange Co. ltd (RedOrange) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * RedOrange licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package redora.html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;

import redora.exceptions.FieldException;
import redora.util.ResourceFileHandler;

//TODO this might not perform very well, make a factory that
//caches the retrieve policies.

/**
 * AntiSamy HTML handler. Put in dirty HTML and clean HTML get's out.
 * @author Redora
 */
public class HtmlHandler {
    private static final Logger l = Logger
               .getLogger("redora.html.HtmlHandler");

    //65k + something extra.
    public final static String MAX_INPUT_SIZE = "100000";

    public static String clean(String policy, String dirtyHtml)
           throws FieldException {
        try {
            Policy pol = Policy.getInstance(ResourceFileHandler
                    .findPolicy(policy));
            pol.setDirective(Policy.MAX_INPUT_SIZE,
                    MAX_INPUT_SIZE); //assuming a max size of 65k
            CleanResults cr = new AntiSamy().scan(dirtyHtml, pol);
            for (Object error : cr.getErrorMessages()) {
                l.log(Level.INFO, "Message in html"
                      + "handling for antisamy: " + error);
            }

            return cr.getCleanHTML();
        } catch (PolicyException e) {
            throw new FieldException("Failed to set"
                    + "or find policy: " + policy, e);
        } catch (ScanException e) {
            throw new FieldException("Failed to"
                    + "scan html: " + dirtyHtml, e);
        } catch (FileNotFoundException e) {
            throw new FieldException("Unable to find"
                    + "policy file for: " + policy, e);
        }
    }
}
